package com.zhang.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhang.pojo.OutputCarBean;
import com.zhang.pojo.ProductBean;
import com.zhang.pojo.UserBean;
import com.zhang.service.IOutputCarService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Api(tags = "出库购物车控制层接口")
@RestController
@RequestMapping("outputCar")
public class OutputCarController {

    @Autowired
    private IOutputCarService outputCarService;

    @ApiOperation("根据客户id和销售员id动态查询出库购物车")
    @GetMapping("findAll/{customId}")
    public List<OutputCarBean> findAll(@PathVariable("customId") int customId,
//                                       @PathVariable("userId") int userId,
                                       HttpServletRequest req) {
        UserBean user = (UserBean) req.getSession().getAttribute("user");

        return outputCarService.findAll(customId, user.getId());
    }


    @ApiOperation("添加出库购物车商品")
    @PostMapping("add")
    public String add( String productJson,
                      Integer customId,
                      Integer userId){
        try {
            JSONObject jsonObject = JSONObject.parseObject(productJson);
            ProductBean productBean = JSONObject.toJavaObject(jsonObject, ProductBean.class);
            outputCarService.add(productBean, customId, userId);
            return "ok";
        } catch (Exception e) {
            return "no";
        }
    }

    @ApiOperation("根据商品id删除商品")
    @DeleteMapping("del/{id}")
    public String del(@PathVariable("id") int id){
        try {
            outputCarService.del(id);
            return "ok";
        } catch (Exception e) {
            return "no";
        }
    }

    @ApiOperation("根据商品id修改出库数量")
    @PutMapping("update/{carId}/{count}")
    public String update(@PathVariable("carId") int carId,
                       @PathVariable("count") int count){
        try {
            outputCarService.update(carId, count);
            return "ok";
        } catch (Exception e) {
            return "no";
        }
    }

    @ApiOperation("出库,先添加销售信息和销售订单，库存再减少")
    @DeleteMapping("delAll/{customId}/{userId}/{total}/{address}")
    public String delAll(@PathVariable("customId") int customId,
                       @PathVariable("userId") int userId,
                       @PathVariable("total") int total,
                       @PathVariable("address") String address){
        try {
            outputCarService.delAll(customId, userId, total, address);
            return "ok";
        } catch (Exception e) {
            return "no";
        }
    }

}
